/**  
 * All rights Reserved, Designed By Android_Robot   
 * @Title:  PersonInfoActivity.java   
 * @Package com.jiyi.activity.zone   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: HYM     
 * @date:   2017-6-15 下午1:43:31   
 * @version V1.0     
 */
package com.jiyi.activity.new_maintenance;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.jiyi.bean.owner.OwnerBean;
import com.jiyi.bean.weibao.CompanyBean;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.util.UserHelp;
import com.jiyi.event.OwnerLogoChangeEvent;
import com.jiyi.inteface.WebApi;
import com.jiyi.widget.StickyNavLayout;
import com.shizhefei.view.indicator.FragmentListPageAdapter;
import com.shizhefei.view.indicator.IndicatorViewPager;
import com.shizhefei.view.indicator.IndicatorViewPager.IndicatorFragmentPagerAdapter;
import com.shizhefei.view.indicator.IndicatorViewPager.OnIndicatorPageChangeListener;
import com.shizhefei.view.indicator.ScrollIndicatorView;
import com.shizhefei.view.indicator.slidebar.ColorBar;
import com.shizhefei.view.indicator.transition.OnTransitionTextListener;
import com.swift.base.ActivityBase;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppBase;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;
import com.swift.utils.DeviceUtil;
import com.swift.utils.GlideUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ClassName: OwnerInfoActivity
 * @Description:TODO(业主信息)
 * @author: HYM
 * @date: *
 */
public class OwnerInfoActivity extends ActivityBase {

	@BindView(R.id.tvBack)
	TextView tvBack;
	@BindView(R.id.tvTitle)
	TextView tvTitle;
	@BindView(R.id.tvSearch)
	TextView tvSearch;

	
	
	@BindView(R.id.snl)
	StickyNavLayout snl;
	@BindView(R.id.id_stickynavlayout_indicator)
	ScrollIndicatorView mIndicator;
	@BindView(R.id.id_stickynavlayout_viewpager)
	ViewPager mViewPager;
	
	

	@BindView(R.id.llBottom)
	LinearLayout llBottom;
	@BindView(R.id.ivLogo)
	ImageView ivLogo;
	@BindView(R.id.tvOwnerName)
	TextView tvOwnerName;
	@BindView(R.id.tvHireDate)
	TextView tvHireDate;
	@BindView(R.id.tvAddress)
	TextView tvAddress;

	IndicatorViewPager indicatorViewPager;
	private LayoutInflater inflate;

	private String[] names = { "设备", "大楼", "数据分析","检测报告" };
	// 业主ID
	private String id;
	private List<CompanyBean> mCompanyBeanList = new ArrayList<CompanyBean>();

	// 进度条
	Dialog dialog;
	OwnerBean ownerBean;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_owner_info);
		ButterKnife.bind(this);
		init();
		EventBus.getDefault().register(this);
	}
	
	@Subscribe
	public void onOwnerLogoChangeEvent(OwnerLogoChangeEvent ownerLogoChangeEvent)
	{
		GlideUtil.load(this, ownerLogoChangeEvent.filePath, ivLogo);
//		Glide.with(this).load(new File(ownerLogoChangeEvent.filePath)).transform(new GlideRoundTransform(this)).into(ivLogo);
//		Glide.with(context).load(new File(ownerLogoChangeEvent.filePath)).asBitmap().centerCrop().placeholder(R.drawable.ic_launcher).into(new BitmapImageViewTarget(ivLogo) {
//            @Override
//            protected void setResource(Bitmap resource) {
//                RoundedBitmapDrawable roundBitmapDrawable =
//                        RoundedBitmapDrawableFactory.create(context.getResources(), resource);
//                roundBitmapDrawable.setCornerRadius(10);
//                ivLogo.setImageDrawable(roundBitmapDrawable);
//            }
//        });
	}
	

	@Override
	protected void onDestroy() {
		hideDialog(dialog);
		EventBus.getDefault().unregister(this);
		super.onDestroy();
	}
	
	/**
	 * @author: HYM
	 * @Title: init
	 * @Description: TODO(这里用一句话描述这个方法的作用) void
	 * @date: 2017-9-12
	 */
	private void init() {
		getIntentData();
		getOwnerInfo();
	}

	/**
	 * @author: HYM
	 * @Title: getPersonInfo
	 * @Description: TODO(这里用一句话描述这个方法的作用) void
	 * @date: 2017-7-4
	 */
	private void getOwnerInfo() {
		if (TextUtils.isEmpty(id)) {
			ToastUtil.getInstances().showMsg("无效的ID");
			finish();
			return;
		}
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		params.put("company_id", id);

		dialog = showDialog(dialog);
		VolleyRequest.StringRequestPost(this, WebApi.MAINTENANCE_OWNER_INFO, "",
				params, new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								String data = obj.getString("data");
								OwnerBean temp = new Gson().fromJson(data, OwnerBean.class);
								setOwnerInfo(temp);
								ownerBean = temp;
								initIndicator();
							} 
							else if (status.equals("404") && info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg("尚未登录或该用户在其他地方登录，请重新登录！");
								//清除环信登录
								UserHelp.getInstance().clearUser(AppBase.Context, true);
								return;
							}
							else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							hideDialog(dialog);
						}
					}

					@Override
					public void stringError(VolleyError error) {
						hideDialog(dialog);
						ToastUtil.getInstances().showMsg(
								R.string.err_http_response);
					}
				});
	}

	/**
	 * @author: HYM
	 * @Title: getIntentData
	 * @Description: TODO(这里用一句话描述这个方法的作用) void
	 * @date: 2017-7-4
	 */
	private void getIntentData() {
		id = getIntent().getStringExtra("id");
		if (TextUtils.isEmpty(id)) {
			ToastUtil.getInstances().showMsg("无效的ID");
			finish();
			return;
		}
	}

	/**
	 * @author: HYM
	 * @Title: initIndicator
	 * @Description: TODO(这里用一句话描述这个方法的作用) void
	 * @date: 2017-6-15
	 */
	private void initIndicator() {
		inflate = LayoutInflater.from(this);
		snl.setAddHeight(-(int) (DeviceUtil.getInstance().getBiLi() * 50 + 0.5f));
		mIndicator.setScrollBar(new ColorBar(this, Color.parseColor("#16B0F4"),
				5));

		// 设置滚动监听
		int selectColorId = R.color.tab_top_on;
		int unSelectColorId = R.color.tab_top;
		int selectSizeId = R.dimen.tab_text_select;
		int unSelectSizeId = R.dimen.tab_text_noselect;

		mIndicator.setOnTransitionListener(new OnTransitionTextListener()
				.setValueFromRes(this, selectColorId, unSelectColorId,
						selectSizeId, unSelectSizeId));

		indicatorViewPager = new IndicatorViewPager(mIndicator, mViewPager);
		indicatorViewPager
				.setAdapter(new MyAdapter(getSupportFragmentManager()));
		indicatorViewPager.setPageOffscreenLimit(2);
		indicatorViewPager.setOnIndicatorPageChangeListener(new OnIndicatorPageChangeListener() {
			
			@Override
			public void onIndicatorPageChange(int preItem, int currentItem) {
				Log.e("  preItem ", preItem+"");
				Log.e("  currentItem ", currentItem+"");
				if (currentItem == 3 || currentItem == 2) {
					showBottom(false);
					snl.setAddHeight(0);
				}
				else {
					showBottom(true);
					snl.setAddHeight(-(int) (DeviceUtil.getInstance().getBiLi() * 50 + 0.5f));
				}
			}
		});
	}

	private class MyAdapter extends IndicatorFragmentPagerAdapter {

		public MyAdapter(FragmentManager fragmentManager) {
			super(fragmentManager);
		}

		@Override
		public int getCount() {
			return names.length;
		}

		@Override
		public View getViewForTab(int position, View convertView,
				ViewGroup container) {
			if (convertView == null) {
				convertView = inflate.inflate(R.layout.tab_top, container,
						false);
			}
			TextView textView = (TextView) convertView;
			textView.setText(names[position % names.length]);
			textView.setPadding(20, 0, 20, 0);
			
			return convertView;
		}

		@Override
		public Fragment getFragmentForPage(int position) {
			Fragment curFragment = null;
			Bundle bundle = null;
			switch (position) {
			case 0:
				// 设备
				curFragment = new EquipListFragment();
				bundle = new Bundle();
				bundle.putString("company_id", ownerBean.getCompany_id());
				curFragment.setArguments(bundle);
				break;
			case 1:
				// 大楼
				curFragment = new BuildListFragment();
				bundle = new Bundle();
				bundle.putString("company_id", ownerBean.getCompany_id());
				curFragment.setArguments(bundle);
				break;
			case 2:
				// 数据分析
				curFragment = new DataAnalysisFragment();
				bundle = new Bundle();
				bundle.putString("company_id", ownerBean.getCompany_id());
				curFragment.setArguments(bundle);
				break;
			case 3:
				// 检测报告
				curFragment = new CheckReportFragment();
				bundle = new Bundle();
				bundle.putString("company_id", ownerBean.getCompany_id());
				curFragment.setArguments(bundle);
				break;
			default:
				break;
			}

			return curFragment;
		}

		@Override
		public int getItemPosition(Object object) {
			return FragmentListPageAdapter.POSITION_NONE;
		}

	};

	@OnClick({ R.id.tvBack, R.id.tvSearch, R.id.tvAddEquip, R.id.tvAddBuild })
	public void onClick(View view) {
		Intent intent = null;
		switch (view.getId()) {
		case R.id.tvBack:
			finish();
			break;
		case R.id.tvSearch:
			intent = new Intent(this, MoreOwnerInfoActivity.class);
			intent.putExtra("companyId", ownerBean.getCompany_id());
			startActivity(intent);
			break;
		case R.id.tvAddEquip:
			intent = new Intent(this, EquipAddActivity.class);
			intent.putExtra("companyId", ownerBean.getCompany_id());
			startActivity(intent);
			break;
		case R.id.tvAddBuild:
			intent = new Intent(this, BuildAddActivity.class);
			intent.putExtra("companyId", ownerBean.getCompany_id());
			startActivity(intent);
			break;
		default:
			break;
		}
	}

	void setOwnerInfo(OwnerBean ownerBean)
	{
		tvOwnerName.setText(ownerBean.getCompany_name());
		GlideUtil.load(this, ownerBean.getCompany_logo(), ivLogo);
		tvHireDate.setText(ownerBean.getExpire_start_time()+"至"+ownerBean.getExpire_time());
		tvAddress.setText(ownerBean.getCompany_address());
	}
	
	void showBottom(boolean isShow)
	{
		if (isShow) {
			llBottom.setVisibility(View.VISIBLE);
		}
		else {
			llBottom.setVisibility(View.GONE);
		}
	}
}
